package com.cvit.controller;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cvit.model.Msg;
import com.cvit.model.Student;
import com.cvit.model.Time;
import com.cvit.service.StudentService;
import com.cvit.service.TimeService;
import com.cvit.utils.LengthCheck;
import com.cvit.utils.Utils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import freemarker.template.Configuration;
import freemarker.template.Template;
import sun.misc.BASE64Encoder;

@Controller
public class StudentContorller {

	@Autowired
	StudentService studentService;
	@Autowired
	TimeService timeservice;

	private Configuration configuration = null;
	String img_paths = "admissions_images/";

	@SuppressWarnings("deprecation")
	public StudentContorller() {
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
	}
	
	/**
	 * 根据考生号修改打印状态值
	 * */
	@RequestMapping("/updateTicketType")
	@ResponseBody
	public Msg updateTicketType(@RequestParam(value = "eamineeId")String eamineeId){
		studentService.updateTicketByEamineeId(eamineeId);
		return Msg.success();
	}
	
	/**
	 * 根据条件查询学生信息
	 */
	@RequestMapping("/getStudents")
	@ResponseBody
	public Msg getStudents(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Student student) {
		PageHelper.startPage(pn, 10);
		List<Student> students = studentService.getStudnets(student);
		PageInfo<Student> page = new PageInfo<Student>(students, 10);
		return Msg.success().add("pageInfo", page);
	}


	/**
	 * 缴费、报名学生总数
	 */
	@RequestMapping("/getStudentsByPay")
	@ResponseBody
	public Msg getStudentsByPay(Student student) {
		List<Student> students = studentService.getStudnets(student);
		student.setPayType(1);
		List<Student> studentspay = studentService.getStudnets(student);
		return Msg.success().add("notpay",students).add("pay",studentspay);
	}
	
	/**
	 * 根据Id查询
	 */
	@RequestMapping("/getStudentById")
	@ResponseBody
	public Msg getStudentById(@RequestParam("StudentId") String id) {
		Student students = studentService.getStudnetById(id);
		return Msg.success().add("student", students);
	}

	/**
	 * 根据考生号查询
	 */
	@RequestMapping("/getStudentByEamineeId")
	@ResponseBody
	public Msg getStudentByEamineeId(@RequestParam("EamineeId") String eamineeId) {
		Student students = studentService.getStudnetByEamineeId(eamineeId);
		return Msg.success().add("student", students);
	}

	/**
	 * 根据身份证号查询
	 */
	@RequestMapping("/getStudentByCardId")
	@ResponseBody
	public Msg getStudentByCardId(@RequestParam("CardId") String cardId) {
		Student students = studentService.getStudnetByCardId(cardId);
		return Msg.success().add("student", students);
	}

	/**
	 * 根据学生号和身份证号查询
	 */
	@RequestMapping("/getStudentByCardIdAndEamineeId")
	@ResponseBody
	public Msg getStudentByCardIdAndEamineeId(@RequestParam("CardId") String cardId,
			@RequestParam("EamineeId") String eamineeId) {
		Student students = studentService.selectByCardIdAndEamineeId(cardId, eamineeId);
		return Msg.success().add("student", students);
	}

	/**
	 * 注册学生信息
	 */
	@RequestMapping("/addStudent")
	@ResponseBody
	public Msg AddStudent(Student student, HttpServletRequest request) {
		LengthCheck check = new LengthCheck();
		if(check.StringLength(student)==2)
			return Msg.fail().add("code", "数据类型错误或过长");
		if(check.StringLength(student)==1)
			return Msg.fail().add("code", "数据长度过长");
		student.setHeight(student.getHeight().toUpperCase());//所有字母转大写
		String timeId = "1";
		Time time = timeservice.getTimeById(timeId);// 获取可用时间段
		int code = Utils.isTime(time.getStarlTime(), time.getEndTime());
		if (code == 1)// 时间判断
			return Msg.fail().add("code", "未到报名时间");
		if (code == 2)
			return Msg.fail().add("code", "报名已结束");
		if (student.getName().length() == 10)
			return Msg.fail().add("code", "姓名填写有误");
		if (Utils.verForm(student.getCardId()) != true)// 信息验证
			return Msg.fail().add("code", "身份证号填写有误");
		if (Utils.eamineeId(student.getEamineeId()) != true)
			return Msg.fail().add("code", "考生号填写有误");
		if (Utils.Height(student.getHeight()) != true)
			return Msg.fail().add("code", "报名序号填写有误");
		Student studentc = new Student();
		studentc = studentService.selectByCardIdAndEamineeId(student.getCardId(), student.getEamineeId());
		if (Utils.isNull(studentc) != true)// 是否重复注册
			return Msg.fail().add("code", "已注册");
		try {
			String imgUrl = studentService.Url(student, request);
			if (imgUrl == null)// 外部接口校验
				return Msg.fail().add("code", "未知错误");
			if (imgUrl == "5")
				return Msg.fail().add("code", "信息验证失败,请检查身份证号和报考序号");
			if (imgUrl == "6")
				return Msg.fail().add("code", "考生类别验证失败");
			if (imgUrl == "2")
				return Msg.fail().add("code", "姓名验证失败");
			if (imgUrl == "1")// 判断填写考生号
				return Msg.fail().add("code", "考生号验证失败");
			if (imgUrl == "3")
				return Msg.fail().add("code", "报考类别验证失败");
			if (imgUrl == "4")
				return Msg.fail().add("code", "毕业类别验证失败");
			student.setImage(imgUrl);
			String id = studentService.addStudent(student, request);
				return Msg.success().add("Id", id);
		} catch (Exception e) {
			e.printStackTrace();
		}
			return null;
	}

	/**
	 * 修改学生信息
	 */
	@RequestMapping("/updateStudent")
	@ResponseBody
	public Msg UpdateStudent(Student student) {
		LengthCheck check = new LengthCheck();
		if(check.StringLength(student)==2)
			return Msg.fail().add("code", "数据类型错误或过长");
		if(check.StringLength(student)==1)
			return Msg.fail().add("code", "数据长度过长");
		String timeId = "1";
		Time time = timeservice.getTimeById(timeId);// 获取可用时间段
		int code = Utils.isTime(time.getStarlTime(), time.getEndTime());
		if (code == 1) 
			return Msg.fail().add("code", "未到报名时间");
		if (code == 2) 
			return Msg.fail().add("code", "报名已结束");
			if (student.getTelephone() != null) {
				if (Utils.Phone(student.getTelephone()) != true) 
					return Msg.fail().add("code", "电话号填写有误");
					studentService.updateStudent(student);
					return Msg.success();
			} else {
				if (student.getPostalCode() != null) {
					if (Utils.postalCode(student.getPostalCode()) != true) 
						return Msg.fail().add("code", "邮编填写有误");
					if (Utils.Phone(student.getAddrTele()) != true) 
						return Msg.fail().add("code", "电话号填写有误");
					studentService.updateStudent(student);
					return Msg.success();
				} else {
					studentService.updateStudent(student);
					return Msg.success();
				}
			}
	}

	/**
	 * 信息审核(批量)
	 */
	@RequestMapping("/examine")
	@ResponseBody
	public Msg examineStudent(@RequestParam("list") List list) {
		studentService.examineStudent(list);
		return Msg.success();
	}

	/**
	 * 登录验证
	 */
	@RequestMapping("/verifyStudent")
	@ResponseBody
	public Msg verifyStudent(@RequestParam("eamineeId") String eamineeId, @RequestParam("cardId") String cardId) {
		int time = Utils.LoginTime();
		if(time == 1)
			return Msg.fail().add("code", "未到登录时间");
		if(time == 2)
			return Msg.fail().add("code", "登录时间已过");
			String id = studentService.verifyStudent(eamineeId, cardId);
		if (id == null)
			return Msg.fail().add("code", "未注册或身份证号、考生号填写错误");
		else
			return Msg.success().add("Id", id);
	}

	/**
	 * 导出Excel
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/StudentExport")
	public @ResponseBody void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String studentData = "学生信息表";
		if (studentData != "") {
			response.reset(); // 清除buffer缓存
			Map<String, Object> map = new HashMap<String, Object>();
			response.setContentType("application/octet-stream;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(studentData.getBytes(), "iso-8859-1") + ".xlsx");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			XSSFWorkbook workbook = null;
			// 导出Excel对象
			workbook = studentService.exportExcelInfo(studentData);
			OutputStream output;
			try {
				output = response.getOutputStream();
				BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
				bufferedOutPut.flush();
				workbook.write(bufferedOutPut);
				bufferedOutPut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	
	/**
	 * 已缴费  导出Excel
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/StudentExportByPay")
	public @ResponseBody void exportPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String studentData = "缴费信息表";
		if (studentData != "") {
			response.reset(); // 清除buffer缓存
			Map<String, Object> map = new HashMap<String, Object>();
			response.setContentType("application/octet-stream;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(studentData.getBytes(), "iso-8859-1") + ".xlsx");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			XSSFWorkbook workbook = null;
			workbook = studentService.exportExcelInfoPay(studentData);
			OutputStream output;
			try {
				output = response.getOutputStream();
				BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
				bufferedOutPut.flush();
				workbook.write(bufferedOutPut);
				bufferedOutPut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 已审核  导出Excel
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/StudentExportByA")
	public @ResponseBody void exportA(HttpServletRequest request, HttpServletResponse response) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String studentData = "审核信息表";
		if (studentData != "") {
			response.reset(); // 清除buffer缓存
			Map<String, Object> map = new HashMap<String, Object>();
			response.setContentType("application/octet-stream;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(studentData.getBytes(), "iso-8859-1") + ".xlsx");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			XSSFWorkbook workbook = null;
			workbook = studentService.exportExcelInfoA(studentData);
			OutputStream output;
			try {
				output = response.getOutputStream();
				BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
				workbook.write(bufferedOutPut);
				bufferedOutPut.flush();
				bufferedOutPut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 导出同意承诺书并未缴费
	 * */
	@RequestMapping("/StudentExportByB")
	public @ResponseBody void exportB(HttpServletRequest request, HttpServletResponse response) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String studentData = "未缴费人员信息表";
		if (studentData != "") {
			response.reset(); // 清除buffer缓存
			Map<String, Object> map = new HashMap<String, Object>();
			response.setContentType("application/octet-stream;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(studentData.getBytes(), "iso-8859-1") + ".xlsx");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			XSSFWorkbook workbook = null;
			workbook = studentService.exportExcelInfoB(studentData);
			OutputStream output;
			try {
				output = response.getOutputStream();
				BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
				workbook.write(bufferedOutPut);
				bufferedOutPut.flush();
				bufferedOutPut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	/**
	 * 下载图片文件夹到桌面
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/download")
	@ResponseBody
	public void downloads(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String img_path = "admissions_images/";
		String fileName = "image_file";
		studentService.downloads(request, response,img_path,fileName);
	}
	
	/**
	 * 导出已通过审核人员   生成Word
	 * @throws Exception 
	 * */
	@ResponseBody
	@RequestMapping("/StudentDoc")
	public Msg createDoc(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
				String dir = request.getSession().getServletContext().getRealPath("/");// 总路径
				String ticketPath = "StudentWord/";
				String fileName = "Student_word_zip";
				String ticketFilePath = dir + ticketPath;
				Student student = new Student();
				student.setPayType(1);
				Writer out = null;
				String gender = "";
				String ExamineeType = "";
				String GraduationType = "";
				String ApplyType = "";
				configuration.setClassForTemplateLoading(this.getClass(), "/com/cvit/utils");
				Template t = null;
				// test.ftl为要装载的模板
				t = configuration.getTemplate("StudentWord.ftl");
				t.setEncoding("utf-8");
					List<Student> list = studentService.getStudnets(student);
					for(int i = 0 ; i < list.size() ; i++){
						if(list.get(i).getGender()==1){
							gender = "男";
						}else{
							gender = "女";
						}
						if(list.get(i).getExamineeType() == 1){
							ExamineeType = "城镇应届";
						}else if(list.get(i).getExamineeType() == 2){
							ExamineeType = "农村应届";
						}else if(list.get(i).getExamineeType() == 3){
							ExamineeType = "城镇往届";
						}else{
							ExamineeType = "农村往届";
						}
						if(list.get(i).getGraduationType()==1){
							GraduationType = "高中";
						}else if(list.get(i).getGraduationType()==2){
							GraduationType = "中等师范";
						}else if(list.get(i).getGraduationType()==3){
							GraduationType = "中等专业学校";
						}else if(list.get(i).getGraduationType()==4){
							GraduationType = "职业高中学校";
						}else if(list.get(i).getGraduationType()==5){
							GraduationType = "技工学校";
						}else{
							GraduationType = "其他学校";
						}
						if(list.get(i).getApplyType() == 1){
							ApplyType = "文史";
						}else{
							ApplyType = "理工";
						}
					Map map = new HashMap();
						map.put("image", getimg(request, list.get(i).getEamineeId(),dir));
						map.put("name", list.get(i).getName());
						map.put("gender", gender);
						map.put("card_id", list.get(i).getCardId());
						map.put("eaminee_id", list.get(i).getEamineeId());
						map.put("birthday", list.get(i).getBirthday());
						map.put("nation", list.get(i).getNation());
						map.put("examinee", ExamineeType);
						map.put("gratype", GraduationType);
						map.put("password", list.get(i).getPassword());
						map.put("apply_type", ApplyType);
						map.put("regions", list.get(i).getRegions());
						map.put("city", list.get(i).getCity());
						map.put("grad_school", list.get(i).getGradSchool());
						map.put("intheclass", list.get(i).getIntheclass());
						map.put("mailing_address", list.get(i).getMailingAddress());
						map.put("postal", list.get(i).getPostalCode());
						map.put("addressee", list.get(i).getAddressee());
						map.put("addr_tele", list.get(i).getAddrTele());
						map.put("telephone", list.get(i).getTelephone());
						map.put("volunteer_one", list.get(i).getVolunteerOne());
						map.put("volunteer_two", list.get(i).getVolunteerTwo());
						map.put("volunteer_three", list.get(i).getVolunteerThree());
						map.put("volunteer_four", list.get(i).getVolunteerFour());
						map.put("volunteer_five", list.get(i).getVolunteerFive());
						map.put("promise_time", df.format(list.get(i).getPromiseTime()));
					File ticketFile = new File(ticketFilePath);
					if (!ticketFile.exists()) {
						ticketFile.mkdirs();
					}
					// 输出文档路径及名称
					File outFile = new File(ticketFilePath, list.get(i).getEamineeId() + ".doc");
						out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
						t.process(map, out);
					}
					out.close();
					studentService.downloads(request, response,ticketPath,fileName);
				return Msg.success();
	}

	private String getimg(HttpServletRequest request, String eamineeId, String dir) {
		StringBuilder path = new StringBuilder(dir + img_paths);
		String imgPath = path + eamineeId + ".jpg";
		InputStream in = null;
		byte[] map = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(imgPath);
			map = new byte[in.available()];
			in.read(map);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(map);// 返回Base64编码过的字节数组字符串
	}

}
